package com.chang.multithread.CAS.Volatile;


import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

public class AtomicIntegera {
    public static void main(String[] args) {
/*        AtomicInteger i=new AtomicInteger(0);//                   当前值   使用之后的值
        System.out.println(i.incrementAndGet());//++i 自增              1          1
        System.out.println(i.getAndIncrement());//i++  谁在前先用谁      1          2
        System.out.println(i.getAndAdd(3));//先值再加,自定义设置增加多少  2          5
        System.out.println(i.addAndGet(3));//先加再获取值                8          8*/

        AtomicInteger i=new AtomicInteger(5);
       /*                                 //参数使用lambda表达式
        System.out.println(i.getAndUpdate(x -> x * 10));//先值在更新   5           50
        System.out.println(i.get());*/
        updateAndSet(i,x->x+2);
        System.out.println(i.get());
    }
    public static void updateAndSet(AtomicInteger i, IntUnaryOperator operator){//函数式接口  实现原理
        while (true){
            int prev = i.get();
            int next=operator.applyAsInt(prev);
            if (i.compareAndSet(prev, next)){
                break;
            }
        }
    }
}
